package org.dromara.common.wukong.service.impl;

import com.alibaba.fastjson2.JSON;
import lombok.RequiredArgsConstructor;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.model.OkHttpUtils;
import org.dromara.common.wukong.constant.WuKongUserConstant;
import org.dromara.common.wukong.dto.*;
import org.dromara.common.wukong.properties.WuKongImProperties;
import org.dromara.common.wukong.service.UserService;

import java.io.IOException;
import java.util.Collections;
import java.util.List;


/**
 * 用户业务
 * @Author: Stars
 * @Date: 2025/3/10 21:13
 */
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final WuKongImProperties wuKongImProperties;

    @Override
    public void registerOrLogin(UserTokenDTO userToken) throws IOException {
        Response response = OkHttpUtils.post(wuKongImProperties.getUrl() + WuKongUserConstant.USER_TOKEN, userToken.convertToMap());
        if (response.code() != 200) {
            throw new IOException("用户注册或登录失败" + response.body().string());
        }
    }

    @Override
    public List<String> queryUserOnlineStatus(UserOnlineStatusQueryDTO userOnlineStatusQuery) throws IOException {
        Response response = OkHttpUtils.post(WuKongUserConstant.USER_ONLINESTATUS, userOnlineStatusQuery.convertToMap());
        if (response.code() != 200) {
            throw new IOException("查询用户在线状态失败" + response.body().string());
        }
        String str = response.body().string();
        if (StringUtils.isNotEmpty(str)) {
            return JSON.parseArray(str, String.class);
        }
        return Collections.emptyList();
    }

    @Override
    public void addSystemAccounts(UserSystemUIdsAddDTO userSystemUIdsAdd) throws IOException {
        Response response = OkHttpUtils.post(wuKongImProperties.getUrl() + WuKongUserConstant.USER_SYSTEMUIDS_ADD, userSystemUIdsAdd.convertToMap());
        if (response.code() != 200) {
            throw new IOException("添加系统账号失败" + response.body().string());
        }
    }

    @Override
    public void removeSystemAccounts(UserSystemUIdsRemoveDTO userSystemUIdsRemove) throws IOException {
        Response response = OkHttpUtils.post(wuKongImProperties.getUrl() + WuKongUserConstant.USER_SYSTEMUIDS_REMOVE, userSystemUIdsRemove.convertToMap());
        if (response.code() != 200) {
            throw new IOException("移除系统账号失败" + response.body().string());
        }
    }

    @Override
    public void kickUserDevice(UserDeviceQuitDTO userDeviceQuit) throws IOException {
        Response response = OkHttpUtils.post(wuKongImProperties.getUrl() + WuKongUserConstant.USER_DEVICE_QUIT, userDeviceQuit.convertToMap());
        if (response.code() != 200) {
            throw new IOException("踢出用户设备失败" + response.body().string());
        }
    }
}
